package com.example.interceptor;

import cn.hutool.core.util.StrUtil;
import com.example.thread.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //  1.  获取请求头上的id
        String id = request.getHeader("id");
        if (StrUtil.isBlank(id)){
            log.info("id为空");
            return false;
        }

        //  2.  将id参数放到ThreadLocal中
        UserThreadLocal.set(id);
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
